﻿using MainFrame.ApplicationService.Dto.TaskInfo;
using MainFrame.ApplicationService.Model;
using MainFrame.Common;
using MainFrame.Common.Interface;
using Qianke.Common;
using Qianke.Common.EntityFramework;
using Qianke.Common.EntityFramework.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace MainFrame.WebApi
{
    public class EntityFrameworkController<TModel, TKey, TAddDto, TUpdateDto, TGetPageDto, TService> :IController
   where TAddDto : class
        where TUpdateDto : class
        where TService : IApplicationService<TModel, TKey, TAddDto, TUpdateDto, TGetPageDto, TokenInfo>, new()
    {

        [Dependency]
        public TService service { set; get; }


        public virtual Task<ReturnInfo> GetModel(Entity<TKey> dto)
        {
            return service.GetModel(dto);
        }

        public virtual Task<ReturnInfo> GetPage(TGetPageDto dto)
        {
            return service.GetPage(dto);
        }

        public virtual Task<ReturnInfo> Delete(Entity<TKey> dto)
        {
            return service.Delete(dto);
        }

        public virtual async Task<ReturnInfo> SaveModel()
        {
            var requestParam = this.GetService<HttpRequestParam>();
            var dataId = requestParam.ParamObj["Id"].SaveToVal(default(TKey));
            if (default(TKey).Equals(dataId))
            {
                var addDto = requestParam.ParamObj.ToObject<TAddDto>();
                var result = addDto.Validate();
                if (result.resultcode != "200") return result;
                return await service.Add(addDto);
            }
            else
            {
                var updateDto = requestParam.ParamObj.ToObject<TUpdateDto>();
                var result = updateDto.Validate();
                if (result.resultcode != "200") return result;
                return await service.Update(updateDto);
            }
        }

    }
}
